#!/usr/bin/python
# -*-  coding: UTF8 -*- 

import config
import sys
sys.path.append(config.PROJECT_HOME) #先要把自己的项目目录加入path
from django.core.management import setup_environ #这是重头戏，全靠它了
from stock import settings #介绍自已人
setup_environ(settings) #安排自己人
#干活去吧
import os
import string
import time
import datetime
import numpy
from stock.gphq import models
from django.db import connection, transaction
from workmanager import * 

def do_job(args):
    global g_mutex
    global records
    # global rxhqs, gbbqs

    if (len(args)==0):
        return False

    code = args[0]
    rxhqs = models.RXHQ.objects.filter(CODE=code)
    gbbqs = models.GBBQ.objects.filter(CODE=code)
    """
    rxhq_list = []
    for rxhq in rxhqs:
        if (rxhq.CODE==code):
            rxhq_list.append(rxhq)
    gbbq_list = []
    for gbbq in gbbqs:
        if (gbbq.CODE==code):
            gbbq_list.append(gbbq)

    """
    if (len(gbbqs)==0):
        return False

    latest_gbbq = gbbqs[0]
    recs = []
    pratio = 0
    for rxhq in rxhqs:
        rec = {}
        rec['TOTAL'] = latest_gbbq.TOTAL #最新总股本
        for gbbq in gbbqs:
            if (rxhq.JYRQ >= gbbq.BGRQ):
                rec['REAL'] = gbbq.TOTAL #当日总股本
                rec['FLOW'] = gbbq.REAL #当日流通股
                rec['TOR'] = round(rxhq.VOL / gbbq.REAL * 100.0, 4) if gbbq.REAL > 0 else round(rxhq.VOL / gbbq.TOTAL * 100.0, 4)
                # print gbbq.REAL
                # print rxhq.VOL
                break
                
        ratio = round(rec['REAL'] / rec['TOTAL'] * 1.0, 2)
        pratio = ratio if pratio == 0 else pratio
        rec['CODE'] = rxhq.CODE
        rec['JYRQ'] = rxhq.JYRQ
        rec['OPEN'] = rxhq.OPEN * ratio
        rec['HIGH'] = rxhq.HIGH * ratio
        rec['LOW'] = rxhq.LOW * ratio
        rec['CLOSE'] = rxhq.CLOSE * ratio
        rec['PCLOSE'] = rxhq.PCLOSE * pratio
        rec['PHIGH'] = rxhq.PHIGH *  pratio
        rec['PLOW'] = rxhq.PLOW *  pratio
        rec['VOL'] = round(latest_gbbq.REAL * rec['TOR'] / 100.0, 2) if latest_gbbq.REAL > 0 else round(latest_gbbq.TOTAL * rec['TOR'] / 100.0, 2)
        rec['AMT'] = rxhq.AMT
        rec['CHG'] = round((rec['CLOSE'] / rec['PCLOSE'] - 1) * 100.0, 2)
        rec['AVG'] = round(rec['AMT'] / rec['VOL'], 2)
        """
        print rec['JYRQ']
        print round(rxhq.AMT / rxhq.VOL, 2)
        print ratio
        print pratio
        print rec['TOR']
        print rec['VOL']
        print rec['AMT']
        print rec['FLOW']
        print rec['REAL']
        print rec['TOTAL']
        print rec['AVG']
        """
        recs.append(rec)
        pratio = ratio

    g_mutex.acquire()
    print "正在处理 %4s 股票......" % (code.encode('UTF8'))
    i = 0
    for rec in recs:
        records.append(rec)
        i += 1
    print "共处理 %4d 条记录" % (i)
    g_mutex.release()

@transaction.commit_on_success
def save_kzhq():
    global records

    for rec in records:
        print "正在处理 " + rec['CODE'].encode('UTF8') + " 股票 " + str(rec['JYRQ'])[0:10].encode('UTF8') + "日数据......"
        kzhq = models.KZHQ(CODE=rec['CODE'], JYRQ=rec['JYRQ'], OPEN=rec['OPEN'], HIGH=rec['HIGH'], LOW=rec['LOW'], CLOSE=rec['CLOSE'], PCLOSE=rec['PCLOSE'], PHIGH=rec['PHIGH'], PLOW=rec['PLOW'], VOL=rec['VOL'], AMT=rec['AMT'], TOR=rec['TOR'], CHG=rec['CHG'], AVG=rec['AVG'], SPV=0)
        kzhq.save()


if __name__ == '__main__':  
    global g_mutex
    global records

    g_mutex = threading.Lock()
    records = []

    start = time.time()  

    cursor = connection.cursor()
    cursor.execute('delete from gphq_kzhq')
    transaction.commit_unless_managed()

    gpdms = models.GPDM.objects.all()

    codes = []
    for gp in gpdms:
        codes.append(gp.CODE)

    # work_manager =  WorkManager(codes, do_job, 10)#或者work_manager =  WorkManager(10000, 20)  
    # work_manager.wait_allcomplete()  
    do_job(['0000006'])

    save_kzhq()

    end = time.time()  
    print end - start
